<template>
  <el-dialog :title="id ? 'Edit' : 'Insert'" :before-close="onClose">
    <el-form
      ref="formEle"
      label-width="140px"
      :model="roleForm"
      :rules="roleFormRules"
      @subnmit.prevent="handleSubmit"
    >
      <el-form-item label="Role Name" prop="name">
        <el-input v-model="roleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="Permission" prop="permissions">
        <el-cascader
          style="width: 100%"
          v-model="roleForm.permissions"
          :options="permissionList"
          :props="permissionProps"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="Status" prop="status">
        <el-switch v-model="roleForm.status"></el-switch>
      </el-form-item>
      <el-form-item>
        <button type="submit" hidden>Submit</button>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="handleSubmit" :loading="isSubmitting">Submit</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { getRoleInfo, submitRole } from '@/api/role'
import { getRuleList } from '@/api/rule'
import { ref, watch, nextTick } from 'vue'

// 1. define props
interface PropsType {
  id: number | null;
}

const props = defineProps<PropsType>()

// 2. get permission list
const permissionList = ref<RuleType[]>([])
const permissionProps = { multiple: true, label: 'menu_name', value: 'id', checkStrictly: true, emitPath: false }

function handleGetPermissionList() {
  getRuleList().then(res => {
    permissionList.value = res
  })
}

handleGetPermissionList()

// 3. initialize data
const roleForm = ref<{ name: string, permissions: number[], status: boolean }>({
  name: '',
  permissions: [],
  status: false
})

const roleFormRules = {
  name: [
    { required: true, message: 'Please input role name' }
  ],
  permissions: [
    { required: true, message: 'Please select permission' }
  ]
}

watch(() => props.id, handleGetRoleData, { immediate: true })

function handleGetRoleData() {
  if (props.id) {
    getRoleInfo(props.id).then(res => {

      roleForm.value = {
        name: res.role_name,
        permissions: res.rules.split(',').map(item => +item),
        status: Boolean(res.status)
      }

    }
    )
  }
}


// 4. submit
const emits = defineEmits(['update:modelValue', 'update:id', 'submit'])

const formEle = ref(null)
const isSubmitting = ref(false)

function handleSubmit() {
  const form = formEle.value as any

  form.validate((valid: boolean) => {
    if (valid) {
      isSubmitting.value = true
      submitRole(Number(props.id), {
        role_name: roleForm.value.name,
        checked_menus: roleForm.value.permissions,
        status: Number(roleForm.value.status) as 0 | 1
      }).then(() => {
        onClose()
        emits('submit')
      }).finally(() => {
        isSubmitting.value = false
      })
    }
  })

}

// 5. reset form
function onClose() {
  const form = formEle.value as any

  form.resetFields()
  roleForm.value.permissions = []
  // ! This is a bug of element-plus: https://github.com/element-plus/element-plus/issues/3890
  nextTick(() => {
    form.clearValidate()
    emits('update:modelValue', false)
    emits('update:id', null)
  })
}

</script>